<template>
  <div class="data-table-container layout-padding">
    <el-card class="layout-padding-auto" shadow="hover">
      <el-form ref="queryFormRef" :model="state.tableData.param.params" inline>
        <el-form-item class="!mr-4" prop="uid">
          <el-input v-model="state.tableData.param.params.uid"
                    placeholder="请输入批次号码" size="default"/>
        </el-form-item>
        <el-form-item class="!mr-4" prop="inType" style="width: 11%">
          <el-select v-model="state.tableData.param.params.inType"
                     clearable
                     placeholder="请选择入库类型"
                     size="default">
            <el-option
                v-for="item in state.inTypeList"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="!mr-4" prop="stockTypeId" style="width: 11%">
          <el-select v-model="state.tableData.param.params.stockTypeId"
                     clearable
                     placeholder="请选择仓库"
                     size="default">
            <el-option
                v-for="item in state.stockTypeList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-auth="'user.list'" class="!mr-4">
          <el-button size="default" type="primary" @click="getTableData">
            <el-icon>
              <ele-Search/>
            </el-icon>
            查询
          </el-button>
        </el-form-item>
        <el-form-item v-auth="'user.list'" class="!mr-4">
          <el-button size="default" type="primary" @click="onHandleResetFields">
            <el-icon>
              <ele-Refresh/>
            </el-icon>
            重置
          </el-button>
        </el-form-item>
        <el-form-item v-auth="'user.list'" class="!mr-4">
          <el-button size="default" type="success" @click="downloadTemplate">
            <el-icon>
              <ele-Download/>
            </el-icon>
            模版下载
          </el-button>
        </el-form-item>
        <el-form-item v-auth="'user.list'" class="!mr-4">
          <el-button size="default" type="warning" @click="onOpenAddIn('add')">
            <el-icon>
              <ele-Upload/>
            </el-icon>
            商品入库
          </el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="state.tableData.loading" :data="state.tableData.data" highlight-current-row
                style="width: 100%"
                @sort-change="handleSortChange">
        <el-table-column label="ID" prop="id" show-overflow-tooltip/>
        <el-table-column label="入库类型" prop="inTypeName" show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="in_type" :value="scope.row.inType"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="单据日期" prop="receiptDate" show-overflow-tooltip/>
        <el-table-column label="仓库" prop="stockTypeName" show-overflow-tooltip/>
        <el-table-column label="供应商" prop="supplierName" show-overflow-tooltip/>
        <el-table-column label="数量" prop="quantity" show-overflow-tooltip/>
        <el-table-column label="金额小计" prop="totalAmount" show-overflow-tooltip/>
        <el-table-column label="审核状态" prop="approvalStatus" show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="approval_status" :value="scope.row.approvalStatus"></dict-tag>
          </template>
        </el-table-column>
        <!--        <el-table-column label="备注" prop="remark"/>-->
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button
                size="small"
                text
                type="primary" @click="onOpenInfo('info',scope.row)">
              查看详情
            </el-button>
            <el-button v-if="scope.row.approvalStatus==='0'"
                       size="small"
                       text
                       type="primary" @click="onRowAdd(scope.row)">
              通过
            </el-button>
            <el-button v-if="scope.row.approvalStatus==='0'"
                       size="small"
                       text
                       type="danger" @click="onRowDel(scope.row)">不通过
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:current-page="state.tableData.param.pageNum"
                     v-model:page-size="state.tableData.param.pageSize" :page-sizes="[10, 20, 30]" :pager-count="5"
                     :total="state.tableData.total" background class="mt15"
                     layout="total, sizes, prev, pager, next, jumper"
                     @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange">
      </el-pagination>
    </el-card>
    <stockDialog ref="stockDialogRef" @refresh="getTableData()"/>
    <infoDialog ref="dialogRef" @refresh="getTableData()"/>
  </div>
</template>

<script lang="ts" name="systemUser" setup>
import {defineAsyncComponent, getCurrentInstance, onMounted, reactive, ref} from 'vue';
import {ElLoading, ElMessage, ElMessageBox} from 'element-plus';
import {stockInApi} from "/@/api/store/stock/in";
import {stockTypeApi} from "/@/api/store/stock/type";
import {dictDataApi} from "/@/api/sys/dictData";
import DictTag from "/@/components/DictTag/index.vue";
import {download} from "/@/utils/ruoyi.js";

const {proxy} = getCurrentInstance();
const {in_type, approval_status} = proxy.useDict("in_type", "approval_status");

// 引入组件
const stockDialog = defineAsyncComponent(() => import('/src/views/store/stock/in/dialog.vue'));
const infoDialog = defineAsyncComponent(() => import('/src/views/store/stock/in/infoDialog.vue'));

// 定义变量内容
const stockDialogRef = ref();
const dialogRef = ref();
const queryFormRef = ref();
const state = reactive<SysUserState>({
  tableData: {
    data: [],
    total: 0,
    loading: false,
    param: {
      pageNum: 1,
      pageSize: 10,
      params: {
        uid: '',
        inType: '',
        stockTypeId: '',
      },
    }
  },
  stockTypeList: [],
  inTypeList: [],
});


const handleSortChange = (data: any) => {
  if (data.order) {
    if (data.order.indexOf('asc') > -1) {
      state.tableData.param.sortOrder = 'asc'
    } else {
      state.tableData.param.sortOrder = 'desc'
    }
    state.tableData.param.sortName = data.prop
  }
  getTableData();
};

// 初始化表格数据
const getTableData = () => {
  state.tableData.loading = true;
  stockInApi()
      .getTableData(state.tableData.param)
      .then((res) => {
        state.tableData.data = res.data.records;
        state.tableData.total = res.data.total;
        state.tableData.loading = false;
      })
      .catch(() => {
        state.tableData.loading = false;
      });
};

// 删除用户
const onRowDel = (row: any) => {
  ElMessageBox.confirm(`此操作将此数据审核不通过，是否继续?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    row.approvalStatus = 2;
    stockInApi()
        .approve(row)
        .then(() => {
          getTableData();
          ElMessage.success('删除成功');
        });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

const onRowAdd = (row: any) => {
  ElMessageBox.confirm(`此操作将此数据审核通过，是否继续?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    row.approvalStatus = 1;
    stockInApi()
        .approve(row)
        .then(() => {
          getTableData();
          ElMessage.success('审核通过');
        })
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};


const onOpenInfo = (type: string, row: RowUserType) => {
  dialogRef.value.openDialog(type, row);
};

// 打开新增用户弹窗
const onOpenAddIn = (type: string) => {
  stockDialogRef.value.openDialog(type);
};

// 分页改变
const onHandleSizeChange = (val: number) => {
  state.tableData.param.pageSize = val;
  getTableData();
};
// 分页改变
const onHandleCurrentChange = (val: number) => {
  state.tableData.param.pageNum = val;
  getTableData();
};
// 页面加载时
onMounted(() => {
  getTableData();

  // 仓库数据
  stockTypeApi()
      .findAll()
      .then(res => {
        state.stockTypeList = res.data;
      })

  // 入库类型
  dictDataApi()
      .getDictByType("in_type")
      .then(res => {
        state.inTypeList = res.data;
      })

});
// 重置查询表单
const onHandleResetFields = () => {
  queryFormRef.value.resetFields();
  getTableData();
};

// 导入模板下载
const downloadTemplate = () => {
  let downloadLoadingInstance = ElLoading.service({
    text: "正在下载数据，请稍候",
    spinner: "el-icon-loading",
    background: "rgba(0, 0, 0, 0.7)",
  })
  stockInApi()
      .downloadTemplate()
      .then(res => {
        download(res, '商品入库导入模板.xlsx');
        downloadLoadingInstance.close();
      }).catch(() => {
  })
};

</script>
